package com.veal98.tree;

import com.veal98.bean.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BinaryTreePreorderTraversal_144 {

    // 递归
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        res.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);

        return res;
    }

    // 迭代
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        // 辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 工作指针
        TreeNode cur = root;

        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                // 根
                res.add(cur.val);
                // 左
                cur = cur.left;
            } else {
                cur =  stack.pop();
                // 右
                cur = cur.right;
            }
        }

        return res;
    }

}
